package com.yanqu.road.dao.impl.player;

import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.impl.TempDataObjectDao;
import com.yanqu.road.entity.player.UserPassTransport;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class UserPassTransportDaoImpl extends TempDataObjectDao<UserPassTransport> {

	public Map<Integer, UserPassTransport> getUserPassTransport(long userId) {
		ResultSet rs = null;
		CallableStatement call = null;
		Map<Integer, UserPassTransport> data = new ConcurrentHashMap<>();
		String sql = "select * from t_u_pass_transport where userId=?";
		try {
			getDb().setConnName(DbNameStrategy.getUserDb());
			call = getDb().getConnection().prepareCall(sql);
			call.setLong(1, userId);
			rs = call.executeQuery();
			while (rs.next()) {
				UserPassTransport item = parse(rs);
				data.put(item.getTemplateId(),item);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			getDb().closeConnection(call, rs);
		}
		return data;
	}

	@Override
	protected boolean addData(UserPassTransport data) {
		PreparedStatement call = null;
		String sql = "INSERT INTO t_u_pass_transport(userId,templateId,createTime) VALUES(?,?,?)";
		try {
			getDb().setConnName(DbNameStrategy.getUserDb());
			call = getDb().getConnection().prepareStatement(sql);
			int i = 1;
			call.setLong(i++, data.getUserId());
			call.setInt(i++, data.getTemplateId());
			call.setLong(i++, data.getCreateTime());
			return call.executeUpdate() > 0;
		} catch (Exception e) {
			logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
		} finally {
			getDb().closeConnection(call, null);
		}
		return false;
	}

	@Override
	protected boolean updateData(UserPassTransport data) {
		PreparedStatement call = null;
		String sql = "UPDATE t_u_pass_transport SET createTime=? WHERE userId=? and templateId=?";
		try {
			getDb().setConnName(DbNameStrategy.getUserDb());
			call = getDb().getConnection().prepareStatement(sql);
			int i = 1;
			call.setLong(i++, data.getCreateTime());
			call.setLong(i++, data.getUserId());
			call.setInt(i++, data.getTemplateId());
			return call.executeUpdate() > 0;
		} catch (Exception e) {
			logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
		} finally {
			getDb().closeConnection(call, null);
		}
		return false;
	}

	@Override
	protected UserPassTransport parseData(ResultSet rs) throws SQLException {
		UserPassTransport data = new UserPassTransport();
		data.setUserId(rs.getLong("userId"));
		data.setTemplateId(rs.getInt("templateId"));
		data.setCreateTime(rs.getLong("createTime"));
		return data;
	}
}
